<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-item">
        <span class="label">部门：</span>
        <dept-tree-select
          v-model="queryParams.deptId"
          placeholder="选择部门"
          width="250px"
          clearable
          @change="fetchData"
        />
      </div>
      <div class="filter-item">
        <span class="label">日期：</span>
        <el-date-picker
          v-model="queryParams.date"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
          style="width: 180px;"
          @change="fetchData"
        />
      </div>
      <div class="filter-item">
        <el-button
          type="primary"
          icon="el-icon-refresh"
          @click="refreshData"
          :loading="refreshLoading"
        >
          刷新统计
        </el-button>
      </div>
      
      <!-- 公式说明提示图标 -->
      <div class="filter-item formula-help">
        <el-tooltip placement="bottom" effect="light" max-width="400">
          <div slot="content">
            <p><strong>计算公式说明：</strong></p>
            <p>发苗率 = 已发苗面积 / 已收苗款面积 × 100%</p>
            <p>移栽完成率 = 已移栽面积 / 已发苗面积 × 100%</p>
            <p>总移栽率 = 已移栽面积 / 已收苗款面积 × 100%</p>
            <p>植保完成率 = 已植保面积 / 已发苗面积 × 100%</p>
            <p>总植保率 = 已植保面积 / 已收苗款面积 × 100%</p>
            <p>移栽面积计算 = 移栽株数 / 1100 (亩)</p>
          </div>
          <i class="el-icon-question help-icon"></i>
        </el-tooltip>
      </div>
    </div>

    <!-- 表格区域（移到最上方） -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column prop="deptName" label="部门" min-width="180" fixed="left" />
        <el-table-column label="苗情统计" align="center">
          <el-table-column prop="paidArea" label="已收苗款面积" align="right" width="120">
            <template slot-scope="scope">
              {{ scope.row.paidArea }}
            </template>
          </el-table-column>
          <el-table-column prop="seedlingDeliveredArea" label="已发苗面积" align="right" width="120">
            <template slot-scope="scope">
              {{ scope.row.seedlingDeliveredArea }}
            </template>
          </el-table-column>
          <el-table-column prop="seedlingRemainingArea" label="未发苗面积" align="right" width="120">
            <template slot-scope="scope">
              {{ scope.row.seedlingRemainingArea }}
            </template>
          </el-table-column>
          <el-table-column prop="seedlingDeliveryRatio" label="发苗率" align="right" width="100">
            <template slot-scope="scope">
              {{ scope.row.seedlingDeliveryRatio }}%
            </template>
          </el-table-column>
          <el-table-column prop="seedlingTodayArea" label="今日发苗面积" align="right" width="120">
            <template slot-scope="scope">
              {{ scope.row.seedlingTodayArea }}
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="移栽统计" align="center">
          <el-table-column prop="transplantRatio" label="移栽完成率" align="right" width="120">
            <template slot-scope="scope">
              {{ scope.row.transplantRatio }}%
            </template>
          </el-table-column>
          <el-table-column label="总移栽率" align="right" width="120">
            <template slot-scope="scope">
              {{ calculateTotalRatio(scope.row.transplantArea, scope.row.paidArea) }}%
            </template>
          </el-table-column>
          <el-table-column prop="transplantCount" label="已移栽株数" align="right" width="120">
            <template slot-scope="scope">
              {{ formatNumber(scope.row.transplantCount) }}
            </template>
          </el-table-column>
          <el-table-column label="已移栽面积" align="right" width="120">
            <template slot-scope="scope">
              {{ calculateTransplantArea(scope.row.transplantCount) }}
            </template>
          </el-table-column>
          <el-table-column prop="transplantTodayCount" label="今日移栽株数" align="right" width="120">
            <template slot-scope="scope">
              {{ formatNumber(scope.row.transplantTodayCount) }}
            </template>
          </el-table-column>
          <el-table-column label="今日移栽面积" align="right" width="120">
            <template slot-scope="scope">
              {{ calculateTransplantArea(scope.row.transplantTodayCount) }}
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="植保统计" align="center">
          <el-table-column prop="pestControlRatio" label="植保完成率" align="right" width="120">
            <template slot-scope="scope">
              {{ scope.row.pestControlRatio }}%
            </template>
          </el-table-column>
          <el-table-column label="总植保率" align="right" width="120">
            <template slot-scope="scope">
              {{ calculateTotalRatio(scope.row.pestControlArea, scope.row.paidArea) }}%
            </template>
          </el-table-column>
          <el-table-column prop="pestControlArea" label="已植保面积" align="right" width="120">
            <template slot-scope="scope">
              {{ scope.row.pestControlArea }}
            </template>
          </el-table-column>
          <el-table-column prop="pestControlTodayArea" label="今日植保面积" align="right" width="120">
            <template slot-scope="scope">
              {{ scope.row.pestControlTodayArea }}
            </template>
          </el-table-column>
          <el-table-column prop="pestControlGrowerCount" label="已植保农户数" align="right" width="120">
            <template slot-scope="scope">
              {{ scope.row.pestControlGrowerCount }}
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </div>

    <!-- 概览卡片区域 -->
    <div class="overview-cards" style="margin-top: 20px;">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-title">已收苗款面积</div>
            <div class="stat-value">{{ overviewData.paidArea || 0 }} 亩</div>
            <div class="stat-desc">农户数：{{ overviewData.paidCount || 0 }}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-title">已发苗面积</div>
            <div class="stat-value">{{ overviewData.seedlingDeliveredArea || 0 }} 亩</div>
            <div class="stat-desc">
              发苗率：{{ overviewData.seedlingDeliveryRatio || 0 }}%
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-title">今日发苗面积</div>
            <div class="stat-value">{{ overviewData.seedlingTodayArea || 0 }} 亩</div>
            <div class="stat-desc">
              剩余：{{ overviewData.seedlingRemainingArea || 0 }} 亩
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-title">统计日期</div>
            <div class="stat-value">{{ overviewData.statDate || "-" }}</div>
            <div class="stat-desc">
              更新：{{ overviewData.updateTime ? formatDateTime(overviewData.updateTime) : "-" }}
            </div>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="8">
          <div class="stat-card dark-card">
            <div class="stat-title">移栽情况</div>
            <div class="stat-value">{{ overviewData.transplantRatio || 0 }}%</div>
            <div class="stat-detail">
              <div class="detail-item">
                <span class="detail-label">已移栽株数：</span>
                <span class="detail-value">{{ formatNumber(overviewData.transplantCount) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">已移栽面积：</span>
                <span class="detail-value">{{ calculateTransplantArea(overviewData.transplantCount) }} 亩</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">总移栽率：</span>
                <span class="detail-value">{{ calculateTotalRatio(calculateTransplantArea(overviewData.transplantCount, false), overviewData.paidArea) }}%</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">剩余株数：</span>
                <span class="detail-value">{{ formatNumber(overviewData.transplantRemainingCount) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">今日移栽株数：</span>
                <span class="detail-value">{{ formatNumber(overviewData.transplantTodayCount) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">今日移栽面积：</span>
                <span class="detail-value">{{ calculateTransplantArea(overviewData.transplantTodayCount) }} 亩</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">已开始移栽农户数：</span>
                <span class="detail-value">{{ overviewData.transplantStartedGrowerCount || 0 }}</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-card dark-card">
            <div class="stat-title">植保情况</div>
            <div class="stat-value">{{ overviewData.pestControlRatio || 0 }}%</div>
            <div class="stat-detail">
              <div class="detail-item">
                <span class="detail-label">已植保面积：</span>
                <span class="detail-value">{{ overviewData.pestControlArea || 0 }} 亩</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">总植保率：</span>
                <span class="detail-value">{{ calculateTotalRatio(overviewData.pestControlArea, overviewData.paidArea) }}%</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">剩余面积：</span>
                <span class="detail-value">{{ overviewData.pestControlRemainingArea || 0 }} 亩</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">今日植保面积：</span>
                <span class="detail-value">{{ overviewData.pestControlTodayArea || 0 }} 亩</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">已植保农户数：</span>
                <span class="detail-value">{{ overviewData.pestControlGrowerCount || 0 }}</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-card dark-card">
            <div class="stat-title">农户情况</div>
            <div class="stat-value">{{ overviewData.seedlingDeliveredGrowerCount || 0 }}</div>
            <div class="stat-detail">
              <div class="detail-item">
                <span class="detail-label">已发苗农户数：</span>
                <span class="detail-value">{{ overviewData.seedlingDeliveredGrowerCount || 0 }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">已收苗款农户数：</span>
                <span class="detail-value">{{ overviewData.paidCount || 0 }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">未开始移栽农户数：</span>
                <span class="detail-value">{{ overviewData.transplantRemainingGrowerCount || 0 }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">未植保农户数：</span>
                <span class="detail-value">{{ overviewData.pestControlRemainingCount || 0 }}</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <echarts-card
            title="发苗率统计"
            :options="seedlingChartOptions"
            height="350px"
          />
        </el-col>
        <el-col :span="12">
          <echarts-card
            title="移栽&植保完成率"
            :options="transplantPestChartOptions"
            height="350px"
          />
        </el-col>
      </el-row>
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="24">
          <echarts-card
            title="各部门数据对比"
            :options="deptCompareChartOptions"
            height="400px"
          />
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import DeptTreeSelect from '@/components/DeptTreeSelect.vue'
import EchartsCard from '@/components/EchartsCard.vue'

export default {
  name: 'StatisticsOverview',
  components: {
    DeptTreeSelect,
    EchartsCard
  },
  data() {
    return {
      queryParams: {
        deptId: undefined,
        date: new Date().toISOString().split('T')[0]
      },
      loading: false,
      refreshLoading: false,
      tableData: [],
      overviewData: {} // 保存总部数据用于概览展示
    }
  },
  computed: {
    seedlingChartOptions() {
      // 过滤掉总部数据
      const filteredData = this.tableData.filter(item => item.deptType !== 0)
      const deptNames = filteredData.map(item => item.deptName)
      const deliveredData = filteredData.map(item => item.seedlingDeliveredArea)
      const remainingData = filteredData.map(item => item.seedlingRemainingArea)
      const ratioData = filteredData.map(item => item.seedlingDeliveryRatio)

      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['已发苗面积', '未发苗面积', '发苗率']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: deptNames,
            axisLabel: {
              rotate: 30,
              interval: 0
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '面积(亩)',
            position: 'left'
          },
          {
            type: 'value',
            name: '百分比(%)',
            position: 'right',
            max: 100,
            min: 0
          }
        ],
        series: [
          {
            name: '已发苗面积',
            type: 'bar',
            stack: '面积',
            emphasis: { focus: 'series' },
            data: deliveredData
          },
          {
            name: '未发苗面积',
            type: 'bar',
            stack: '面积',
            emphasis: { focus: 'series' },
            data: remainingData
          },
          {
            name: '发苗率',
            type: 'line',
            yAxisIndex: 1,
            data: ratioData,
            symbolSize: 8,
            itemStyle: {
              color: '#f56c6c'
            }
          }
        ]
      }
    },
    transplantPestChartOptions() {
      // 过滤掉总部数据
      const filteredData = this.tableData.filter(item => item.deptType !== 0)
      const deptNames = filteredData.map(item => item.deptName)
      const transplantRatioData = filteredData.map(item => item.transplantRatio)
      const pestControlRatioData = filteredData.map(item => item.pestControlRatio)
      
      // 计算总移栽率和总植保率
      const totalTransplantRatioData = filteredData.map(item => 
        this.calculateTotalRatio(this.calculateTransplantArea(item.transplantCount, false), item.paidArea)
      )
      const totalPestControlRatioData = filteredData.map(item => 
        this.calculateTotalRatio(item.pestControlArea, item.paidArea)
      )

      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['移栽完成率', '总移栽率', '植保完成率', '总植保率']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: deptNames,
            axisLabel: {
              rotate: 30,
              interval: 0
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '百分比(%)',
            max: 100,
            min: 0
          }
        ],
        series: [
          {
            name: '移栽完成率',
            type: 'bar',
            emphasis: { focus: 'series' },
            data: transplantRatioData,
            itemStyle: {
              color: '#67c23a'
            }
          },
          {
            name: '总移栽率',
            type: 'bar',
            emphasis: { focus: 'series' },
            data: totalTransplantRatioData,
            itemStyle: {
              color: '#95d475'
            }
          },
          {
            name: '植保完成率',
            type: 'bar',
            emphasis: { focus: 'series' },
            data: pestControlRatioData,
            itemStyle: {
              color: '#409eff'
            }
          },
          {
            name: '总植保率',
            type: 'bar',
            emphasis: { focus: 'series' },
            data: totalPestControlRatioData,
            itemStyle: {
              color: '#79bbff'
            }
          }
        ]
      }
    },
    deptCompareChartOptions() {
      // 过滤掉总部数据
      const filteredData = this.tableData.filter(item => item.deptType !== 0)
      const deptNames = filteredData.map(item => item.deptName)
      const todayTransplantData = filteredData.map(item => item.transplantTodayCount)
      // 转换今日移栽面积
      const todayTransplantAreaData = filteredData.map(item => 
        this.calculateTransplantArea(item.transplantTodayCount, false)
      )
      const todayPestControlData = filteredData.map(item => item.pestControlTodayArea)
      const todaySeedlingData = filteredData.map(item => item.seedlingTodayArea)

      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['今日移栽(株)', '今日移栽(亩)', '今日植保(亩)', '今日发苗(亩)']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: deptNames,
            axisLabel: {
              rotate: 30,
              interval: 0
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '数量'
          }
        ],
        series: [
          {
            name: '今日移栽(株)',
            type: 'bar',
            emphasis: { focus: 'series' },
            data: todayTransplantData
          },
          {
            name: '今日移栽(亩)',
            type: 'bar',
            emphasis: { focus: 'series' },
            data: todayTransplantAreaData
          },
          {
            name: '今日植保(亩)',
            type: 'bar',
            emphasis: { focus: 'series' },
            data: todayPestControlData
          },
          {
            name: '今日发苗(亩)',
            type: 'bar',
            emphasis: { focus: 'series' },
            data: todaySeedlingData
          }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.loading = true
      const params = {}
      if (this.queryParams.deptId) {
        params.deptId = this.queryParams.deptId
      }
      if (this.queryParams.date) {
        params.date = this.queryParams.date
      }

      request.get('/statistics', { params })
        .then(response => {
          if (response && response.length > 0) {
            // 计算移栽面积
            this.tableData = response.map(item => {
              // 如果后端未提供移栽面积，在前端计算
              if (!item.transplantArea && item.transplantCount) {
                item.transplantArea = Number((item.transplantCount / 1100).toFixed(1))
              }
              return item
            })
            
            // 找到总部数据
            const headquartersData = response.find(item => item.deptType === 0)
            if (headquartersData) {
              this.overviewData = headquartersData
              // 如果后端未提供移栽面积，在前端计算
              if (!this.overviewData.transplantArea && this.overviewData.transplantCount) {
                this.overviewData.transplantArea = Number((this.overviewData.transplantCount / 1100).toFixed(1))
              }
            } else {
              this.overviewData = response[0]
            }
          } else {
            this.tableData = []
            this.overviewData = {}
          }
        })
        .catch(error => {
          console.error('获取统计数据失败:', error)
          this.$message.error('获取统计数据失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    refreshData() {
      this.refreshLoading = true
      request.put('/statistics/updateAll')
        .then(() => {
          this.$message.success('统计数据更新成功')
          this.fetchData() // 重新获取数据
        })
        .catch(error => {
          console.error('更新统计数据失败:', error)
          this.$message.error('更新统计数据失败')
        })
        .finally(() => {
          this.refreshLoading = false
        })
    },
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return ''
      return dateTimeStr.replace('T', ' ')
    },
    formatNumber(num) {
      if (num === undefined || num === null) return '0'
      return num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')
    },
    // 计算移栽面积（株数/1100）
    calculateTransplantArea(count, format = true) {
      if (!count || isNaN(count)) return format ? '0.0' : 0
      const area = Number(count) / 1100
      return format ? area.toFixed(1) : Number(area.toFixed(1))
    },
    // 计算总比率
    calculateTotalRatio(value, total) {
      if (!value || !total || isNaN(value) || isNaN(total) || Number(total) === 0) return '0.0'
      const ratio = (Number(value) / Number(total)) * 100
      return ratio.toFixed(1)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-item {
  margin-right: 20px;
  display: flex;
  align-items: center;

  .label {
    margin-right: 8px;
  }
}

.overview-cards {
  margin-bottom: 20px;
}

.stat-card {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  height: 100%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  &.dark-card {
    background: #f5f7fa;
  }

  .stat-title {
    font-size: 14px;
    color: #606266;
    margin-bottom: 10px;
  }

  .stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 10px;
  }

  .stat-desc {
    font-size: 12px;
    color: #909399;
  }

  .stat-detail {
    margin-top: 10px;

    .detail-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 6px;
      font-size: 13px;
      color: #606266;
    }
  }
}

.el-table {
  margin-top: 20px;
}

.charts-container {
  margin-top: 20px;
}

.formula-help {
  margin-left: auto; /* 将图标推到右侧 */
  cursor: pointer;
}

.help-icon {
  font-size: 18px;
  color: #409EFF;
  border: 1px solid #409EFF;
  border-radius: 50%;
  padding: 5px;
}
</style> 